/**
 * @required vue-validator
 * @author guocailee
 */
let errorMessage = {
  email: '您输入的邮箱格式有误',
  mobile: '您输入的手机格式有误',
  required: '此项为必录项',
  repeat: '两项输入不一致',
  answerequal: '回答有误，请重试',
  username: '账号格式有误'
}

/* eslint-disable no-useless-escape*/
export const isEmail = (val) => {
  return /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(val)
}

export const isMobile = (val) => {
  return /^1+\d{10}$/.test(val)
}

let validatorRule = (Vue) => {
  if (validatorRule.installed) {
    return
  }
  if (!Vue.validator) {
    console.warn('Validator Rule is required Vue-Vlaidator, You Should Use It Before.')
    return
  }

  Vue.validator('email', {
    message: errorMessage.email,
    check(val) {
      return isEmail(val)
    }
  })

  Vue.validator('mobile', {
    message: errorMessage.mobile,
    check(val) {
      return isMobile(val)
    }
  })

  Vue.validator('repeat', {
    message: errorMessage.repeat,
    check(val, map) {
      return val === map
    }
  })

  Vue.validator('answerequal', {
    message: errorMessage.answerequal,
    check(val, map) {
      return val === map
    }
  })

  Vue.validator('required', {
    message(field) {
      return errorMessage.required
    },
    check: Vue.validator('required')
  })
  Vue.validator('username', {
    message(field) {
      return errorMessage.username
    },
    check(val, map) {
      return isEmail(val) || isMobile(val)
    }
  })
  Vue.validator('minlength', {
    message(field, len) {
      return `请输入至少${len}个字符`
    },
    check: Vue.validator('minlength')
  })
}

export default validatorRule
